<?php

    /**
     * Simple
     *
     * @package      Core
     * @subpackage   Url_Engine
     *
     * @license      GNU Lesser General Public Licence see LICENCE-LGPL file or http://www.gnu.org/licenses/lgpl.html
     */
    class Core_Url_Engine_Simple implements Core_Url_Engine_Interface
    {

    ////////////////////////////////////////////////////////////////////////////
	//                                Variables                               //
	////////////////////////////////////////////////////////////////////////////

		protected $_urlspe = null;

		protected $_urlhttps = null;

	////////////////////////////////////////////////////////////////////////////
	//                                 Methods                                //
	////////////////////////////////////////////////////////////////////////////

		/**
		 * Constructor
		 */
		public function __construct()
		{
		}

		/**
		 * Destructor
		 */
		public function __destruct()
		{
			unset($this);
		}

		/**
		 * Parses some url components
		 *
		 * @param        string      $scriptNamePath : /path/index.php
		 * @param        string      $pathinfo : the path info part of the url (part between script name and query)
		 * @param        array       $params : url parameters (query part e.g. $_REQUEST)
		 * @throws		 Core_ArgumentException
		 * @throws		 Core_ArgumentNullException
		 * @return       Core_Url_Action
		 */
		public function parse($scriptNamePath, $pathinfo, array $params)
		{
            if ($scriptNamePath === null) {
				throw new Core_ArgumentNullException('scriptNamePath is a null reference');
			}

            if (strlen(trim($scriptNamePath)) == 0) {
				throw new Core_ArgumentException('scriptNamePath is a zero-length string');
			}

            if ($pathinfo === null) {
				throw new Core_ArgumentNullException('pathinfo is a null reference');
			}

			return new Core_Url_Action($params);
		}

		/**
		 * Creates a URL object with the given action datas
		 *
	 	 * @param        Core_Url_Action     $url : information about the action
		 * @return       Core_Url            the url corresponding to the action
		 */
		public function create(Core_Url_Action $urlAction)
		{
			$scriptName = $this->_getScript(
											$urlAction->getRequestType(),
											$urlAction->getParam('module'),
											$urlAction->getParam('action')
										);

			$url = new Core_Url($scriptName, $urlAction->getParams(), '');

			// With certain type, parameters aren't in the URL (passed by POST f.e.)
            if (in_array($urlAction->getRequestType(), array('xml', 'json', 'soap'))) {
				$url->clearParam();
			}

			return $url;
		}

	////////////////////////////////////////////////////////////////////////////
	//                            Protected methods                           //
	////////////////////////////////////////////////////////////////////////////

		/**
		 * Reads the configuration and gets the script path corresponding to the given parameters
		 *
		 * @param        string      $requestType
		 * @param        string      $module
		 * @param        string      $action
		 * @throws		 Core_ArgumentException
		 * @throws		 Core_ArgumentNullException
		 */
		protected function _getScript($requestType, $module = null, $action = null)
		{
            if ($requestType === null) {
				throw new Core_ArgumentNullException('requestType is a null reference');
			}

            if (strlen(trim($requestType)) == 0) {
				throw new Core_ArgumentException('requestType is a zero-length string');
			}

			$registry = Zend_Registry::getInstance();
            $script = $registry['config']->urlengine->defaultEntrypoint;

			if ($this->_urlhttps == null) {
				$this->_urlhttps = array();
				$selectors = preg_split("/[\s,]+/", $registry['config']->urlengine->simple_urlengine_https);

				foreach ($selectors as $sel2) {
					$this->_urlhttps[$sel2] = true;
				}
			}

			$usehttps = false;
			if ($action && isset($this->_urlhttps[$module .'~'. $action .'@'. $requestType])) {
				$usehttps = true;
			} else if ($module && isset($this->_urlhttps[$module .'~*@'. $requestType])) {
				$usehttps = true;
			} else if (isset($this->_urlhttps['@'. $requestType])) {
				$usehttps = true;
			}

			if (count($registry['config']->simple_urlengine_entrypoints->toArray())) {
				if ($this->_urlspe == null) {
					$this->_urlspe = array();

					foreach ($registry['config']->simple_urlengine_entrypoints as $entrypoint => $sel) {
						$selectors = preg_split("/[\s,]+/", $sel);

						foreach ($selectors as $sel2) {
							$this->_urlspe[$sel2] = $entrypoint;
						}
					}
				}

				if ($action && isset($this->_urlspe[$s1 = $module .'~'. $action .'@'. $requestType])) {
					$script = $this->_urlspe[$s1];
				} else if ($module && isset($this->_urlspe[$s2 = $module .'~*@'. $requestType])) {
					$script = $this->_urlspe[$s2];
				} else if (isset($this->_urlspe[$s3 = '@'. $requestType])) {
					$script = $this->_urlspe[$s3];
				}
			}

			if (!$registry['config']->urlengine->multiview) {
				$script .= $registry['config']->urlengine->entrypointExtension;
			}

            $base = '';
            if ($registry['end'] == 'admin') {
                $base = trim($registry['config']->urlengine->basePath, '/') . '/serum/';
            } else {
                $base = trim($registry['config']->urlengine->basePath, '/') . '/';
            }

			if (substr($base, 0, 1) != '/') {
				$base = '/' . $base;
			}

			if ($usehttps) {
				return 'https://'. $_SERVER['HTTP_HOST'] . $base . $script;
			} else {
				return 'http://'. $_SERVER['HTTP_HOST'] . $base . $script;
			}
		}
   }
